#include "widget.h"
#include "ui_widget.h"

#include <QTimer>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setLayout(ui->verticalLayout);

    client = new QTcpSocket(this);
    connect(client,SIGNAL(readyRead()),this,SLOT(mRead_Data_From_serve()));

    ui->btnDiscon->setEnabled(false);
    ui->btnSend->setEnabled(false);

}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_btnCon_clicked()
{
    client->connectToHost(ui->lineEditAddr->text(), ui->lineEditPort->text().toInt());
    timer = new QTimer(this);
    timer->setSingleShot(true);
    timer->setInterval(5000);

    connect(timer,SIGNAL(timeout()),this,SLOT(onTimeOut()));
    connect(client,SIGNAL(connected()),this,SLOT(onConnected()));
    connect(client,SIGNAL(error(QAbstractSocket::SocketError )),this,SLOT(onError(QAbstractSocket::SocketError )));

    this->setEnabled(false);
    timer->start();
}

void Widget::mRead_Data_From_serve()
{
   ui->textEditRev->moveCursor(QTextCursor::End);
   ui->textEditRev->ensureCursorVisible();
   setInsertColor(Qt::black, client->readAll());
}

void Widget::on_btnSend_clicked()
{
    QByteArray sendData = ui->textEditSend->toPlainText().toUtf8();
    client->write(ui->textEditSend->toPlainText().toUtf8());

    //QBrush::QBrush(const QColor & color);
    //QColor::QColor(Qt::GlobalColor color);
    setInsertColor(Qt::red, sendData);

}

void Widget::on_btnDiscon_clicked()
{

    client->close();
    ui->textEditRev->insertPlainText("终止连接!");
    ui->lineEditAddr->setEnabled(true);
    ui->lineEditPort->setEnabled(true);
    ui->btnCon->setEnabled(true);
    ui->btnDiscon->setEnabled(false);
    ui->btnSend->setEnabled(false);
}

void Widget::onConnected()
{
    timer->stop();
    this->setEnabled(true);
    ui->textEditRev->append("连接成功!");
    ui->lineEditAddr->setEnabled(false);
    ui->lineEditPort->setEnabled(false);
    ui->btnCon->setEnabled(false);
    ui->btnDiscon->setEnabled(true);
    ui->btnSend->setEnabled(true);
}

void Widget::onError(QAbstractSocket::SocketError error)
{

    qDebug() << error;
    ui->textEditRev->insertPlainText("连接出了问题：" + client->errorString());
    this->setEnabled(true);
    on_btnDiscon_clicked();
}

void Widget::onTimeOut()
{
    ui->textEditRev->insertPlainText("连接超时！");
    client->abort();
    this->setEnabled(true);
}

void Widget::setInsertColor(Qt::GlobalColor color, QString str)
{
    QTextCursor cursor = ui->textEditRev->textCursor();
    QTextCharFormat format;
    format.setForeground(QBrush(QColor(color)));
    cursor.setCharFormat(format);
    cursor.insertText("\n" + str);
}
